package com.coldwindblows.blog.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Base64;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 工具类
 * Created by ColdWindBlows on 2018/07/04
 *
 */
public class Tools {
	private static final Random random = new Random();
	
	@SuppressWarnings("resource")
	public static void copyFileUsingFileChannels(File source, File dest) throws IOException {
		FileChannel inputChannel = null;
		FileChannel outputChannel = null;
		try {
			inputChannel = new FileInputStream(source).getChannel();
			outputChannel = new FileOutputStream(dest).getChannel();
			outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
		} finally {
			assert inputChannel != null;
			inputChannel.close();
			assert outputChannel != null;
			outputChannel.close();
		}
	}
	
	public static int rand(int min, int max) {
		return random.nextInt(max) % (max - min + 1) + min;
	}
	
	/**
	 * 将容量自动转换 KB,MB,GB
	 * @param value
	 * @return
	 */
	public static String flowAutoShow(double value) {
		// Math.round 方法接受float和double类型，如果参数int，会强转为float，这个时候调用该方法无意义
		int kb = 1024;
		int mb = 1048576;
		int gb = 1073741824;
		double abs = Math.abs(value);
		if(abs > gb) {
			return Math.round(value / gb) + "GB";
		} else if(abs > mb) {
			return Math.round(value / mb) + "MB";
		} else if(abs > kb) {
			return Math.round(value / kb) + "KB";
		}
		
		return Math.round(value) + "";
	}
	
	/**
	 * aes加密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String enAes(String data, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		byte[] encryptedBytes = cipher.doFinal(data.getBytes());
		
		return Base64.getEncoder().encodeToString(encryptedBytes);
	}
	
	/**
	 * aes解密
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String deAes(String data, String key)throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
		byte[] cipherTextBytes = Base64.getDecoder().decode(data);
		byte[] decValue = cipher.doFinal(cipherTextBytes);
		
		return new String(decValue);
	}
	
	/**
	 * 判断字符串是否为数字和有正确的值
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		return null != str && 0 != str.trim().length() && str.matches("\\d*");
	}
 }
